from flask import Blueprint, request, jsonify
from .. import db
from ..models import Code, User
from ..utils.mail import send_verification_email
from datetime import datetime, timedelta
import random, string

auth_bp = Blueprint('auth', __name__)

@auth_bp.route('/send-code', methods=['POST'])
def send_code():
    data = request.get_json()
    email = data.get('email')

    if not email:
        return jsonify({'error': '请输入邮箱'}), 400

    recent_code = Code.query.filter_by(email=email).order_by(Code.created_at.desc()).first()
    if recent_code and (datetime.utcnow() - recent_code.created_at).total_seconds() < 60:
        return jsonify({'error': '验证码发送过于频繁，请稍后再试'}), 429

    code = ''.join(random.choices(string.digits, k=6))
    new_code = Code(email=email, code=code)
    db.session.add(new_code)
    db.session.commit()

    try:
        send_verification_email(email, code)
        return jsonify({'message': '验证码已发送'})
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@auth_bp.route('/verify-code', methods=['POST'])
def verify_code():
    data = request.get_json()
    email = data.get('email')
    code_input = data.get('code')

    if not email or not code_input:
        return jsonify({'error': '缺少参数'}), 400

    latest_code = Code.query.filter_by(email=email).order_by(Code.created_at.desc()).first()
    if (not latest_code or latest_code.code != code_input or
        (datetime.utcnow() - latest_code.created_at).total_seconds() > 300):
        return jsonify({'error': '验证码无效或已过期'}), 400

    user = User.query.filter_by(email=email).first()
    if not user:
        user = User(email=email)
        db.session.add(user)
        db.session.commit()
        add_default_categories(user.id)

    Code.query.filter_by(email=email).delete()
    db.session.commit()

    return jsonify({'message': '登录成功', 'user_id': user.id})

# 默认分类添加逻辑迁移至这里
def add_default_categories(user_id):
    from ..models import Category
    default_categories = [
        {"type": "支出", "name": "餐饮", "icon": "🍔", "color": "#FF9F1A"},
        {"type": "支出", "name": "购物", "icon": "🛍️", "color": "#EF476F"},
        {"type": "支出", "name": "交通", "icon": "🚌", "color": "#06D6A0"},
        {"type": "支出", "name": "娱乐", "icon": "📺", "color": "#118AB2"},
        {"type": "支出", "name": "医疗", "icon": "⛑", "color": "#FFD166"},
        {"type": "收入", "name": "工资", "icon": "💰", "color": "#06D6A0"},
        {"type": "收入", "name": "红包", "icon": "🎁", "color": "#EF476F"},
        {"type": "收入", "name": "理财收益", "icon": "💴", "color": "#118AB2"},
    ]
    for c in default_categories:
        db.session.add(Category(user_id=user_id, **c))
    db.session.commit()

